<template>
  <div class="address">
    <nav-bar>
      <span slot="text">选择地址</span>
    </nav-bar>
    <div class="container">
      <div class="city" @click="$router.push('/searchCity')">
        <span v-if="city && city.name">{{ city.name }}</span>
        <span v-else>请选择</span>
        <i class="iconfont icon-xiala"></i>
      </div>
      <div class="search">
        <i class="iconfont icon-sousuo"></i>
        <input type="text" v-model="searchName" placeholder="请输入城市地址" />
      </div>
    </div>
    <div class="place_list" v-if="placeList.length">
      <ul>
        <li
          v-for="(item, index) in placeList"
          :key="index"
          @click="decideAdd(item)"
        >
          <span>{{ item.name }}</span>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapState } from 'vuex';
import { getUserAddress, searchAddress } from '@/network/getData';
import { Local } from '@/common/storage';

export default {
  data() {
    return {
      city: {},
      searchName: '',
      placeList: [] // 地点列表
    };
  },
  created() {
    this.city = Local.get('city');
    if (!this.city) {
      getUserAddress().then(res => {
        this.city = res.data;
      });
    }
  },
  computed: {
    ...mapState(['lng'])
  },
  methods: {
    ...mapMutations(['SAVE_LOCATION', 'SAVE_ORDER_ADDRESS']),
    // 跳转
    decideAdd(data) {
      if (!this.lng) {
        this.SAVE_LOCATION(data);
      }
      this.SAVE_ORDER_ADDRESS(data.name);
      this.$router.go(-1);
    }
  },
  watch: {
    searchName(value) {
      clearTimeout(this.time);
      this.time = setTimeout(() => {
        if (value !== '') {
          searchAddress(this.city.name, value).then(res => {
            this.placeList = res.data;
          });
        } else {
          this.placeList = [];
        }
      }, 200);
    }
  }
};
</script>

<style lang="less" scoped>
.address {
  width: 100vw;
  height: 100vh;
  background-color: #fff;
  .container {
    width: 100%;
    line-height: 30px;
    display: flex;
    padding: 55px 10px 0;
    font-size: var(--font-size);
    .city {
      flex: 20%;
      text-align: center;
    }
    .search {
      flex: 80%;
      position: relative;
      input {
        width: 100%;
        height: 100%;
        text-indent: 30px;
        border-radius: 6px;
        background-color: #eee;
      }
      i {
        position: absolute;
        top: 0;
        left: 10px;
        font-size: 15px;
      }
    }
  }
  .place_list {
    padding: 10px;
    font-size: var(--font-size);
    li {
      height: 35px;
      line-height: 35px;
      border-bottom: 1px solid #c5c5c5;
    }
  }
}
</style>
